import PageBody from '@/components/school/pageBody';

const app = getApp();
import diyJson from '@/config/diy.js';
import {BASE_CONFIG} from "@/config/app";
import {mapGetters} from "vuex";
import OrderList from '@/components/school/orderList';

export const mixins = {
  components: {
    PageBody, OrderList
  }, computed: mapGetters(['userInfo', 'schoolId', 'isLogin']), data() {
    return {
      themConfig: diyJson.commonStyle
      , rules: []
      , invite: {}
      , tagStyle: {
        img: 'width:100%;display:block;',
        table: 'width:100%',
        video: 'width:100%'
      }
      , scrollTop: 0
      , showLoading: true
      ,chatMsgList: []
      , orderInfo: {},
      pageBody: {
        background: 'white',
        // #ifdef MP
        pageHeight: '100%',
        // #endif
        // #ifdef H5
        pageHeight: app.globalData.windows.pageBody - 70,
        // #endif
      }, sockectClient: undefined,

      chatInputMsg: '',

      socketOpen: false,

      // 消息发送模版
      msgTemplate: {
        // message为消息主体
        "message": '',
        // 发送消息的会员
        "memberInfo": {
          "memberName": "",
          "memberId": "",
          "memberAvatar": ""
        }, // 消息类型：1=文本消息，2=图片，3=富文本消息,4=订单消息
        "msgType": 1, // 聊天类型：订单/客服【当前是客服 写死即可】
        "chatType": "CUSTOMER"
        ,"header": {
          "tenantId": undefined
          , "schoolId": undefined
          , "token": ""
        }
      }
    }
  }, onShow() {
    console.log("websocketUrl", BASE_CONFIG.websocketUrl)
    // 初始化会员消息
    this.initMsmTemplate();
    if (!this.socketOpen) {
      this.initWebSocket();
    }
  }, mounted() {
  }, methods: {

    initMsmTemplate() {
      this.msgTemplate.memberInfo.memberId = this.userInfo.id;
      this.msgTemplate.memberInfo.memberName = this.userInfo.nickName;
      this.msgTemplate.memberInfo.memberAvatar = this.userInfo.avatar;
      this.msgTemplate.header.tenantId = BASE_CONFIG.tenantId;
      this.msgTemplate.header.schoolId = this.schoolId;
    },

    initWebSocket() {
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
        uni.showToast({
          title: "您的浏览器不支持WebSocket"
        })
      } else {
        // 'ws://127.0.0.1:39307/{userId}/{refId}/{chatType}/{tenantId}',
        let url = BASE_CONFIG.websocketUrl;
        url = url.replace("{userId}", this.userInfo.id)
        .replace("{refId}", "CUSTOMER")
        .replace("{chatType}", "CUSTOMER")
        .replace("{tenantId}", BASE_CONFIG.tenantId);

        url=url+"?memberName="+this.userInfo.nickName +"&schoolId="+this.schoolId

        console.log("websocketUrl", url)

        this.sockectClient = new WebSocket(url);

        let that = this;

        this.sockectClient.onopen = function () {
          console.log("Socket 已打开");
          that.socketOpen = true;

          let prams = {...this.msgTemplate};
          that.sendMsgForContent('您好，有事咨询...', 1);

          setTimeout(() => {
            that.scrollBottom();
          }, 1000);
        }

        this.sockectClient.onmessage = function (msg) {
          let res = JSON.parse(msg.data);
          if (res.msgType === 0) {
            that.chatMsgList = res.content;
          } else {
            that.chatMsgList.push(res.content);
          }
          console.log("接收到消息", res);
          that.scrollBottom();
        }

        //关闭事件
        this.sockectClient.onclose = function () {
          console.log("Socket已关闭");
          that.socketOpen = false;
          that.scrollBottom();
        };

        //发生了错误事件
        this.sockectClient.onerror = function () {
          console.log("Socket发生了错误");
          that.socketOpen = false;
          that.scrollBottom();
        }
      }
    }

    // 点击发送消息
    , sendMsg() {
      if (this.chatInputMsg===''){
        return;
      }
      this.sendMsgForContent(this.chatInputMsg);
      this.chatInputMsg = '';
    }

    , sendMsgForContent(msg, msgType) {
      let prams = {...this.msgTemplate};
      prams.message = msg;
      prams.msgType = msgType || 1;
      console.log("发送消息", prams);
      this.sockectClient.send(JSON.stringify(prams));
      this.scrollBottom();
    }

    , scrollBottom() {
      this.$nextTick(()=>{
        this.scrollTop = 100000 * (Math.floor(Math.random() * 100) + 1)
      });
    }
  }
}
